using System;
using System.IO;
using System.Security.Cryptography;
using Ionic.Zip;

namespace Koonfusion.SyncDeploy.Core.Services
{
    internal class FileUtilities
    {
        internal static string GetHash(FileInfo file)
        {
            string hashText = String.Empty;
            string hexValue;

            byte[] fileData = File.ReadAllBytes(file.FullName);
            byte[] hashData = SHA1.Create().ComputeHash(fileData); // SHA1 or MD5


            foreach (var b in hashData)
            {
                hexValue = b.ToString("X").ToLower(); // Lowercase for compatibility on case-sensitive systems
                hashText += (hexValue.Length == 1 ? "0" : "") + hexValue;
            }

            return hashText;
        }

        internal static string GetReletive(DirectoryInfo parent, FileInfo child)
        {
            if (parent == null) throw new ArgumentNullException("parent");
            if (child == null) throw new ArgumentNullException("child");

            var root = parent.FullName.TrimEnd('\\').ToLower();
            var file = child.FullName.ToLower();

            if (!file.Contains(root))
                throw new ArgumentException("Not a valid parent child relationship");

            return file.Replace(root, "").Trim('\\');
        }


        internal static void CompressFile(FileInfo source, FileInfo destination)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (source == null) throw new ArgumentNullException("destination");
            source.Refresh();
            if (!source.Exists)
                throw new ArgumentException(String.Format("File '{0}' doesn't exist", source.FullName), "source");

            using (var zip = new ZipFile())
            {
                zip.AddFile(source.FullName, "");
                Directory.CreateDirectory(destination.DirectoryName);
                zip.Save(destination.FullName);
            }
        }
    }
}